package com.rzico.sbl.ui.order

import android.text.Editable
import android.text.InputFilter
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzg.extend.jackson.JsonUtil
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityDeliverReviewBinding
import com.rzico.sbl.model.CommonData
import com.rzico.sbl.other.privacyStatus
import com.rzico.sbl.other.userRole
import com.rzico.sbl.ui.member.MemberBucketActivity
import com.rzico.sbl.ui.member.MemberDetailActivity
import com.rzico.sbl.ui.member.MemberTicketActivity
import com.rzico.sbl.viewmodel.DeliverViewModel
import com.xinnuo.common.decoration.DividerLRDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.copyStringToClip
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.helper.phoneReplaceWithStar
import com.xinnuo.common.listener._TextWatcher
import com.xinnuo.common.other.DecimalNumberFilter
import com.xinnuo.common.view.FullyGridLayoutManager
import com.xinnuo.common.view.FullyLinearLayoutManager
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.glideExt.loadRoundedImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showBottomPhoneDialog
import com.xinnuo.common_ui.utils.showListDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import net.mikaelzero.mojito.ext.mojito
import net.mikaelzero.mojito.impl.DefaultPercentProgress
import net.mikaelzero.mojito.impl.NumIndicator
import net.mikaelzero.mojito.interfaces.IProgress
import net.mikaelzero.mojito.loader.InstanceLoader
import org.json.JSONArray
import org.json.JSONObject
import kotlin.text.orEmpty

class DeliverReviewActivity : BaseActivity(R.layout.activity_deliver_review) {

    private val mBinding by lazy { ActivityDeliverReviewBinding.bind(getRootView()) }

    // 品牌列表
    private val mBarrelList = ArrayList<CommonData>()

    // 图片列表
    private var mPhotoList = ArrayList<String>()

    private lateinit var mShippingSn: String
    private var mCardId = ""        //会员卡ID
    private var mMemberId = ""      //会员ID
    private var mReceivePhone = ""  //收货电话
    private var mReceiveAdress = "" //收货地址

    private var mOrderMethod = "" //订单类型：线上(online)、报单(offline)
    private var mAmountPaid = ""  //实收金额
    private var mPaperPaid = ""   //实收水票
    private var mLevel = -1       //楼层
    private var barrelPhoto = ""   //还桶
    override fun getViewModel() = get<DeliverViewModel>()

    override fun initData() {
        initTitle(title = "运单审核")

        initLayout()
        initPhotoLayout()

        getData()
        intent.getExtra("shipId")
            .notEmpty {
                getViewModel().getBarrelList(this)
            }
    }

    private fun initLayout() {
        mBinding
            .recycleList
            .apply {
                isNestedScrollingEnabled = false
                layoutManager = FullyLinearLayoutManager(getIContext())

                addItemDecoration(
                    DividerLRDecoration(
                        spaceL = 0f,
                        spaceR = 0f,
                        hasFooter = false
                    )
                )

                mAdapter = SlimAdapter.creator()
                    .register<CommonData>(R.layout.item_dispatch_list) { jector, bean, index ->
                        jector.apply {
                            text(R.id.item_patch_name, bean.name)
                            text(R.id.item_patch_buy, bean.hangQuantity)
                            text(R.id.item_patch_send, bean.quantity)

                            getView<View>(R.id.item_patch_del).isGone = bean.show
                            getView<View>(R.id.item_patch_arrow).isGone = bean.show
                            getView<View>(R.id.item_patch_layout1).isVisible = bean.show
                            getView<View>(R.id.item_patch_layout2).isGone = bean.show
                            getView<View>(R.id.item_patch_layout3)
                                .isVisible = bean.hangQuantity.intValue > 0

                            with<EditText>(R.id.item_patch_back) {
                                if (it.tag != null && it.tag is TextWatcher) {
                                    it.removeTextChangedListener(it.tag as TextWatcher)
                                }

                                it.setText(bean.returnQuantity)
                                it.setSelection(it.text.length)

                                val textWatcher = object : _TextWatcher() {
                                    override fun afterTextChanged(s: Editable) {
                                        bean.returnQuantity = s.toString()
                                    }
                                }
                                it.addTextChangedListener(textWatcher)
                                it.tag = textWatcher
                            }

                            with<EditText>(R.id.item_patch_num) {
                                if (it.tag != null && it.tag is TextWatcher) {
                                    it.removeTextChangedListener(it.tag as TextWatcher)
                                }

                                it.setText(bean.returnQuantity)
                                it.setSelection(it.text.length)

                                val textWatcher = object : _TextWatcher() {
                                    override fun afterTextChanged(s: Editable) {
                                        bean.returnQuantity = s.toString()
                                    }
                                }
                                it.addTextChangedListener(textWatcher)
                                it.tag = textWatcher
                            }

                            clicked(R.id.item_patch_fl) {
                                bean.show.conditionFalse {
                                    showLoopDialog(index)
                                }
                            }
                            clicked(R.id.item_patch_del) {
                                mList.removeAt(index)
                                notifyDataSetChanged()
                            }
                        }
                    }
                    .attachTo(this)
            }
    }

    private fun initPhotoLayout() {
        mBinding.apply {
            photoList.also { layout ->
                layout.isNestedScrollingEnabled = false
                layout.layoutManager = FullyGridLayoutManager(baseContext, 3)
                layout.adapter = SlimAdapter.creator()
                    .register<String>(R.layout.item_photo_grid) { jector, bean, index ->
                        jector.apply {
                            gone(R.id.item_photo_del)

                            with<ImageView>(R.id.item_photo_img) {
                                it.loadRoundedImage(
                                    url = bean,
                                    radius = 10f
                                )
                            }

                            clicked {
                                layout.mojito(R.id.item_photo_img) {
                                    urls(mPhotoList)
                                    position(index, headerSize = 1, footerSize = 1)
                                    autoLoadTarget(false)
                                    setProgressLoader(object : InstanceLoader<IProgress> {
                                        override fun providerInstance(): IProgress {
                                            return DefaultPercentProgress()
                                        }
                                    })
                                    progressLoader { DefaultPercentProgress() }
                                    setIndicator(NumIndicator())
                                }
                            }
                        }
                    }
                    .attachTo(layout)
            }

            (photoList.adapter as SlimAdapter).setDataList(mPhotoList)
        }
    }

    override fun initListener() {
        mShippingSn = intent.getExtra("shippingSn")

        mBinding.apply {
            reviewReal.filters = arrayOf(
                DecimalNumberFilter(),
                InputFilter.LengthFilter(8)
            )

            // 添加回桶
            btAdd.oneClick {
                mBarrelList
                    .isEmpty()
                    .condition {
                        showToast("获取商品信息失败！")
                        return@oneClick
                    }

                showLoopDialog()
            }

            // 拨打电话
            reviewCall.oneClick {
                mReceivePhone.notEmpty {
                    showBottomPhoneDialog(this)
                }
            }

            // 复制地址
            reviewAddrCopy.oneClick {
                copyStringToClip(
                    "${reviewName.textTrim}\n$mReceiveAdress"
                )
                showToast("复制成功！")
            }

            // 查看会员
            reviewMember.oneClick {
                startActivityEx<MemberDetailActivity>(
                    "cardId" to mCardId,
                    "memberId" to mMemberId
                )
            }

            // 历史借桶
            reviewBarrelLl.oneClick {
                mCardId.notEmpty {
                    startActivityEx<MemberBucketActivity>(
                        "cardId" to mCardId,
                        "memberId" to mMemberId
                    )
                }
            }

            // 电子水票
            reviewPaperLl.oneClick {
                mCardId.notEmpty {
                    startActivityEx<MemberTicketActivity>(
                        "cardId" to mCardId,
                        "memberId" to mMemberId
                    )
                }
            }

            // 客户楼层
            reviewFloorLl.oneClick {
                val items = arrayListOf(
                    "有电梯", "1层", "2层", "3层", "4层",
                    "5层", "6层", "7层", "8层", "9层"
                )
                showListDialog(
                    title = "请选择楼层",
                    items = items,
                    index = items.indexOf(reviewFloor.content),
                    listener = { index, hint ->
                        mLevel = index
                        reviewFloor.text = hint
                    }
                )
            }
            htphotoimg.oneClick {
                mBinding.htphotoimg.mojito(barrelPhoto)
            }
            // 提交审核
            btReview.oneClick {
                mMemberId
                    .isEmpty()
                    .condition {
                        showToast("获取会员信息失败")
                        return@oneClick
                    }

                (reviewPageLl.isVisible
                        && reviewPage.content.isEmpty())
                    .condition {
                        showToast("请输入实收纸质水票")
                        return@oneClick
                    }

                (reviewRealLl.isVisible
                        && reviewReal.content.isEmpty())
                    .condition {
                        showToast("请输入实收金额")
                        return@oneClick
                    }

                mList.forEach {
                    it as CommonData
                    it.returnQuantity
                        .isEmpty()
                        .condition {
                            it.returnQuantity = "0"
                        }
                }

                getViewModel()
                    .deliveryReview(
                        "sn" to mShippingSn,
                        "amountPaid" to conditionIf(
                            reviewRealLl.isVisible,
                            reviewReal.content,
                            mAmountPaid
                        ),
                        "paperPaid" to conditionIf(
                            reviewPageLl.isVisible,
                            reviewPage.content,
                            mPaperPaid
                        ),
                        "level" to mLevel,
                        "memo" to reviewMemo.content,
                        "body" to Gson().toJson(mList)
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("审核成功！")

                            // 更新运单列表
                            LiveEventBus
                                .get("deliverList")
                                .post("refresh")

                            // 更新运单详情
                            LiveEventBus
                                .get("deliverDetail")
                                .post("refresh")

                            finishView()
                        }
                    )
            }
        }

        // 观察空桶列表
        getViewModel()
            .mBarrelEvent
            .observe(this) { value ->
                mBarrelList.clear()
                mBarrelList.addItems(value)

                mList.clear()
                mList.addItems(value.filter { it.show })

                mAdapter.setDataList(mList)
            }

        // 观察电子水票
        getViewModel()
            .mTicketEvent
            .observe(this) {
                mBinding.reviewPaper.text = it.toString()
            }
    }

    private fun showLoopDialog(position: Int = -1) {
        val items = mBarrelList.filter {
            mList.none { item -> (item as CommonData).id == it.id }
        }

        items.notEmpty {
            showListDialog(
                title = "请选择品牌",
                items = map { it.name.orEmpty() },
                listener = { index, _ ->
                    if (position > -1) {
                        mList.removeAt(position)
                        mList.add(position, this[index])
                        mAdapter.notifyDataSetChanged()
                    } else {
                        mList.add(this[index])
                        mAdapter.notifyDataSetChanged()
                    }
                }
            )
        }
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .viewBarrel(mShippingSn)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = { json ->
                    val obj = JSONObject(json)

                    mCardId = obj.optNotNull("cardId")
                    mMemberId = obj.optNotNull("memberId")
                    mOrderMethod = obj.optNotNull("orderMethod")
                    mAmountPaid = obj.optNotNull("amountPaid")
                    mPaperPaid = obj.optNotNull("paperPaid")
                    val sellerId = obj.optNotNull("sellerId")
                    val shopOwnerId = obj.optNotNull("shopOwnerId")
                    val objBarrel = obj.optJSONArray("shippingBarrels") ?: JSONArray()
                    if(objBarrel.length()>0){
                        val jsobj = objBarrel.getJSONObject(0)
                        if (TextUtils.isEmpty(jsobj.getString("photo"))||jsobj.getString("photo").equals("null")){
                            mBinding.rlthmsg.gone()
                        }else{
                            mBinding.rlthmsg.visible()
                            barrelPhoto=jsobj.getString("photo")
                            mBinding.htphotoimg.loadRoundedImage(jsobj.getString("photo"))
                        }

                    }else{
                        mBinding.rlthmsg.gone()
                    }
                    mBinding.apply {
                        /*---------------------- 客户信息 ----------------------*/
                        val objReceive = obj.optJSONObject("receiver") ?: JSONObject()
                        mReceivePhone = objReceive.optNotNull("phone")
                        mReceiveAdress = objReceive.optNotNull("areaName")
                        mReceiveAdress += objReceive.optNotNull("address")

                        // 姓名电话
                        reviewName.text = "${objReceive.optNotNull("consignee")}  ${
                            when {
                                userRole in "1,2"
                                        || privacyStatus == "off" -> mReceivePhone

                                else -> mReceivePhone.phoneReplaceWithStar()
                            }
                        }"
                        // 收货地址
                        reviewAddr.text = mReceiveAdress
                        // 会员详情
                        reviewMember.isVisible =
                            userRole in "1,2"
                                    && mCardId.isNotEmpty()
                                    && mMemberId.isNotEmpty()
                        // 历史欠款
                        reviewBefore.text = obj.optNotNull("arrears").formatDecimal()
                        // 历史借桶
                        reviewBarrel.text = obj.optNotEmpty("borrow", "0")
                        // 买家留言
                        reviewMai.text =
                            obj.optNotNull("orderMemo")
                                .notEmpty { reviewMaiLl.visible() }
                        // 商家备注
                        reviewCmemo.text =
                            obj.optNotNull("cardMemo")
                                .notEmpty { reviewCmemoLl.visible() }

                        /*---------------------- 订单信息 ----------------------*/
                        // 订单编号
                        reviewNum.text = obj.optNotNull("orderSn")
                        // 订单类型
                        reviewType.text = when (mOrderMethod) {
                            "online" ->
                                when (obj.optNotNull("paymentPluginId")) {
                                    "ticketPayPlugin" -> "货到付款"
                                    else -> "线上订单"
                                }

                            "ali" ->
                                when (obj.optNotNull("paymentPluginId")) {
                                    "ticketPayPlugin" -> "货到付款"
                                    else -> "支付宝"
                                }

                            "offline" -> "人工报单"
                            "history" -> "人工补单"
                            "nongfu" -> "农夫APP"
                            "meituan" -> "美团"
                            "eleme", "elemengc" -> "饿了么"
                            "jd" -> "京东"
                            "taobao" -> "淘宝"
                            "pinduoduo" -> "拼多多"
                            else -> "其他"
                        }
                        // 支付方式
                        reviewPay.text =
                            obj.optNotNull("payMethodName")
                                .also {
                                    reviewPayLl.isGone = it.isEmpty()
                                }
                        // 实收/结算金额
                        (sellerId == shopOwnerId)
                            .conditionElse(
                                actionTrue = {
                                    reviewHint.text = "实收金额"
                                    reviewAmount.text = mAmountPaid.formatDecimal()
                                },
                                actionFalse = {
                                    reviewHint.text = "结算金额"
                                    reviewAmount.text =
                                        obj.optNotNull("settlementPrice")
                                            .also {
                                                reviewAmountLl.isVisible =
                                                    it.doubleValue > 0.0
                                            }.formatDecimal()
                                }
                            )
                        // 派单留言
                        reviewPai.text =
                            obj.optNotNull("memo")
                                .trimEnd('\n')
                                .notEmpty { reviewPaiLl.visible() }

                        /*---------------------- 配送信息 ----------------------*/
                        // 客户楼层
                        mLevel = objReceive.optInt("level")
                        reviewFloor.text = if (mLevel == 0) "有电梯" else "${mLevel}层"

                        val payMethod = obj.optNotNull("payMethod")
                        reviewPageLl.isVisible = payMethod == "exchange"
                        reviewRealLl.isVisible =
                            payMethod == "exchange"
                                    || payMethod == "cash"
                                    || payMethod == "weixin"
                                    || payMethod == "ali"

                        // 实收水票
                        reviewPage.setText(mPaperPaid)
                        // 实收金额
                        reviewReal.setText(mAmountPaid.formatDecimal())
                        // 电子签名
                        obj.optNotNull("signature")
                            .notEmpty {
                                reviewSignLl.visible()

                                Glide.with(getIContext())
                                    .load(this)
                                    .into(reviewSign)
                            }

                        // 图片列表
                        val objPhoto = obj.optJSONArray("shippingPhotos") ?: JSONArray()
                        mPhotoList.clear()
                        mPhotoList.addItems(
                            JsonUtil.toList(
                                objPhoto.toString(),
                                String::class.java
                            )
                        )
                        mPhotoList.notEmpty {
                            mBinding.photoListLl.visible()
                            (mBinding.photoList.adapter as SlimAdapter).notifyDataSetChanged()
                        }
                    }

                    // 电子水票
                    mCardId.notEmpty {
                        getViewModel().ticketCount(this)
                    }
                }
            )
    }

}